package main

import (
	"context"
	"fmt"

	"github.com/project-flogo/contrib/activity/log"
	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/api"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/engine"

	client "gitee.com/shipnet/flogo-lib.git/trigger/netclient"
)

func main() {

	app := myApp()

	e, err := api.NewEngine(app)

	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	engine.RunEngine(e)
}

func myApp() *api.App {
	app := api.NewApp()

	settings := &client.Settings{
		Network: "tcp",
		Host:    "localhost",
		Port:    "3000",
		Max:     1000,
		STX:     "$",
		ETX:     "\n",
		Timeout: "10s",
	}
	trg := app.NewTrigger(&client.Trigger{}, settings)
	hData, _ := trg.NewHandler(&client.HandlerSettings{
		Type: client.OnData,
	})
	hData.NewAction(RunActivities)

	// hTimeout, _ := trg.NewHandler(&client.HandlerSettings{
	// 	Type: client.OnAny,
	// })
	// hTimeout.NewAction(RunActivities)

	//store in map to avoid activity instance recreation
	act, err := api.NewActivity(&log.Activity{}, map[string]interface{}{})
	if err != nil {
		return app
	}
	activities = map[string]activity.Activity{"log": act}

	return app
}

var activities map[string]activity.Activity

func RunActivities(ctx context.Context, inputs map[string]interface{}) (map[string]interface{}, error) {

	trgOut := &client.Output{}
	trgOut.FromMap(inputs)

	// msg, _ := coerce.ToString(trgOut.AnOutput)
	fmt.Printf("trgOut: %+v\n", trgOut)
	str, err := coerce.ToString(trgOut.Data)
	if err != nil {
		return nil, err
	}
	input := &log.Input{
		Message: str,
	}
	// err = metadata.MapToStruct(m, input, true)
	// if err != nil {
	// 	return nil, err
	// }
	_, err = api.EvalActivity(activities["log"], input)
	if err != nil {
		return nil, err
	}

	reply := &client.Reply{Reply: []byte("ok")}
	return reply.ToMap(), nil
}
